package com.moore.net;

import com.moore.utils.WebUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

// 作用：读取请求，解析请求协议，并保存请求的请求行、请求头、请求数据
public class HttpRequest {
    private String url;
    private String protocol;
    private String[] arr;
    private final Map<String, String> header = new HashMap<>();
    private Map<String, String> params;
    private final InputStream inputStream;
    private final BufferedReader bufferedReader;

    public HttpRequest(Socket socket) {
        try {
            this.inputStream = socket.getInputStream();
            this.bufferedReader = new BufferedReader(new InputStreamReader(this.inputStream));
            requestLine();
            requestHeader();
            requestBody();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    // 请求行
    public void requestLine(){
        // 读取请求行
        String requestLine;
        try {
            requestLine = bufferedReader.readLine();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        if (requestLine == null) {
            throw new IllegalArgumentException("Empty request");
        }
        // 解析请求行
        arr = requestLine.split(" ");
        if (arr.length < 3) {
            throw new IllegalArgumentException("Invalid request line: " + requestLine);
        }
        url = arr[1];
        // 解析url参数
        params = WebUtils.getParams(url);
        url = url.split("\\?")[0];
        protocol = arr[2];
    }

    // 请求头
    public void requestHeader(){
        // 读取请求头（循环获取多个，直到空行结束）
        while (true) {
            String line;
            try {
                line = bufferedReader.readLine();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            if (line == null || line.isEmpty()) {
                break;
            }
            arr = line.split(": ");
            if (arr.length < 2) {
                throw new IllegalArgumentException("Invalid header line: " + line);
            }
            String key = arr[0];
            String value = arr[1];
            header.put(key, value);
        }
    }

    // 请求数据（请求体）
    public void requestBody(){
        // 读取请求数据
        String length = header.get("Content-Length");
        if (length != null) {
            int len = Integer.parseInt(length);
            // 不能使用readLine来接收，有可能多行或没有回车换行
            // 使用字节流接收
            byte[] buffer = new byte[len];
            try {
                inputStream.read(buffer);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public Map<String, String> getParams() {
        return params;
    }

    public String getUrl() {
        return url;
    }

    public String getProtocol() {
        return protocol;
    }
}
